package cn.lee.test.biz;

import cn.lee.test.model.User;
import cn.lee.test.model.UserToken;
import cn.lee.test.service.UserService;
import cn.lee.test.service.UserTokenService;
import cn.lee.test.util.JwtUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : lichl(李承霖)
 * create: 2022/2/24 13:24 周四
 */

@Component
public class LoginBiz{
  
  @Autowired
  private UserService userService;
  
  @Autowired
  private UserTokenService tokenService;
  
  // 用户登录逻辑
  @SneakyThrows // 此注解为lombok插件为了消除trycatch这种模板代码
  public String login(String username, String password){
    
    String jwtToken = "";
    
    User loginUser = userService.checkLogin(username, password);
    if(loginUser != null){
      // 登录成功返回jwt字符串
      jwtToken = JwtUtils.getJwtToken(String.valueOf(loginUser.getId()), loginUser.getUserNickName());
      // 存在更新 不存在添加
      UserToken tokenData = tokenService.getTokenByUserId(loginUser.getId());
      if(tokenData == null){
        // 在token表中创建jwtToken
        UserToken userToken = new UserToken();
        userToken.setUserId(loginUser.getId());
        userToken.setTokenString(jwtToken);
        userToken.setUserNickName(loginUser.getUserNickName());
        tokenService.curd_create(userToken);
      }else{
        tokenData.setTokenString(jwtToken);
        tokenService.curd_update(tokenData);
      }

    }else{
      throw new Exception("password error"); // 这里后期可以将封装自定义异常,抛出前端可用的错误信息;
    }
    return jwtToken;
  }
  
}
